package cn.core.dirs.service;

import cn.core.dirs.ao.FileUploadAO;
import cn.core.tool.exception.CoreException;
import cn.core.tool.service.FileService;
import cn.core.tool.util.CoreTool;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.LinkedHashSet;

/**
 * 文件上传 服务
 */
@Log4j2
@Service
public class FileUploadService {

  @Resource
  private FileService fileService;

  /**
   * 文件上传
   */
  public Collection<String> fileUpload(FileUploadAO fileUploadAO) throws Exception {
    try {
      if (CoreTool.isNullStr(fileUploadAO.getFileModule())) {
        throw new CoreException(CoreException.E_PARAM_ERR);
      }
      if (fileUploadAO.getFile() == null) {
        throw new CoreException(CoreException.E_PARAM_ERR);
      }
      if (fileUploadAO.getFile().length == 0) {
        throw new CoreException(CoreException.E_PARAM_ERR);
      }
      LinkedHashSet<String> r = new LinkedHashSet<>();
      for (MultipartFile multipartFile : fileUploadAO.getFile()) {
        try (InputStream inputStream = multipartFile.getInputStream()) {
          r.add(fileService.getFileUrlByFileStream(IOUtils.toByteArray(inputStream), fileUploadAO.getFileModule(), multipartFile.getOriginalFilename()));
        } catch (IOException e) {
          throw new CoreException(CoreException.E_ERR);
        }
      }
      return r;
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.error(e.getMessage(), e);
      }
      throw e;
    }
  }

}
